<template>
	<div class="page">
		 <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
			 <!-- 搜索框-->
			  <el-form-item prop="isaccount">
					   <el-select v-model="searchForm.isaccount" placeholder="请选择是否报销" size="small" style="width: 100%;">
						 <el-option
						   v-for="item in $dictUtils.getDictList('is_account')"
						   :key="item.value"
						   :label="item.label"
						   :value="item.value">
						 </el-option>
					   </el-select>
			  </el-form-item>
			  <el-form-item prop="type">
					   <el-select v-model="searchForm.type" placeholder="请选择发票类型" size="small" style="width: 100%;">
						 <el-option
						   v-for="item in $dictUtils.getDictList('invoicebill_type')"
						   :key="item.value"
						   :label="item.label"
						   :value="item.value">
						 </el-option>
					   </el-select>
			  </el-form-item>
			  <el-form-item prop="subType">
					   <el-select v-model="searchForm.subType" placeholder="请选择细分发票类型" size="small" style="width: 100%;">
						 <el-option
						   v-for="item in $dictUtils.getDictList('sub_bill_type')"
						   :key="item.value"
						   :label="item.label"
						   :value="item.value">
						 </el-option>
					   </el-select>
			  </el-form-item>
			  <el-form-item prop="invoiceCode">
					 <el-input size="small" v-model="searchForm.invoiceCode" placeholder="发票代码" clearable></el-input>
			  </el-form-item>
			  <el-form-item prop="invoiceNo">
					 <el-input size="small" v-model="searchForm.invoiceNo" placeholder="发票号码" clearable></el-input>
			  </el-form-item>
			  <el-form-item prop="invoiceDate">
					 <el-input size="small" v-model="searchForm.invoiceDate" placeholder="开票日期" clearable></el-input>
			  </el-form-item>
			  <el-form-item prop="payerName">
					 <el-input size="small" v-model="searchForm.payerName" placeholder="购方姓名" clearable></el-input>
			  </el-form-item>
			  <el-form-item prop="sellerName">
					 <el-input size="small" v-model="searchForm.sellerName" placeholder="销方姓名" clearable></el-input>
			  </el-form-item>
			   <el-form-item>
				 <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
				 <el-button @click="resetSearch()" size="small">重置</el-button>
			   </el-form-item>
		   </el-form>
		<!-- 导入导出-->
		<el-dialog title="导入Excel" :visible.sync="isImportCollapse">
			<el-form size="small" :inline="true" v-show="isImportCollapse" ref="importForm">
				<el-form-item>
					<el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
				</el-form-item>
				<el-form-item prop="loginName">
					<el-upload class="upload-demo"
						:action="`${this.$http.BASE_URL}/zhaohang/invoice/web/userticket/sysUserTicket/import`"
						:on-success="uploadSuccess" :show-file-list="true">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
					</el-upload>
				</el-form-item>
			</el-form>
		</el-dialog>
		<el-dialog title="新增发票" :visible.sync="addInvoiceDlalog" width="50%">
			<el-form :model="addInvoiceForm" size="small" label-width="140px" ref="addInvoiceForms"
				v-loading="addInvoiceFormLoading">
				<el-row :gutter="15">
					<el-col :span="12">
						<el-form-item label="报销类型" prop="invoiceType"
							:rules="[{required: true, message:'报销类型不能为空', trigger:'blur'}]">
							<el-select v-model="addInvoiceForm.invoiceType" placeholder="请选择" style="width: 100%;">
								<el-option v-for="item in $dictUtils.getDictList('ticket_type')" :key="item.value"
									:label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="报销类别" prop="accountType"
							:rules="[{required: true, message:'报销类别不能为空', trigger:'blur'}]">
							<el-cascader  placeholder="请选择"
								v-model="addInvoiceForm.accountType" :props="{
								expandTrigger: 'hover',checkStrictly: true,label: 'name',value: 'id',
								children: 'children',}" :key="cascaderKey" size="small" ref="bussinessTypes"
								@change="handleChange" clearable
								@click.native="handleSelect" :popper-class="'cascader1'"
								:options="valueData">
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="报销说明" prop="invoiceContent"
							:rules="[{required: true, message:'报销说明不能为空', trigger:'blur'}]">
							<el-input v-model="addInvoiceForm.invoiceContent"></el-input>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="附件" prop="image"
						    :rules="[{required: true, message:'附件不能为空', trigger:'blur'}]">
						          <!-- :on-preview="(file, fileList) => {$window.location.href = (file.response && file.response.url) || file.url}"   :on-preview="(file) => {document.location.href = file.url}"-->
						      <el-upload ref="image"
						        :action="`${this.$http.BASE_URL}/zh/test/uploadInvoice`"
						        :headers="{token: $cookie.get('token')}"                    
						        :on-preview="(file) => {$window.open ((file.response && file.response.url) || file.url,'_blank') }"
						        :on-success="(response, file, fileList) => {
						           addInvoiceForm.image = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
						        }"
						        :on-remove="(file, fileList) => {
						          $http.post(`/dlyrlTest/deleteFile?path=${(file.response && file.response.url) || file.url}`).then(({data}) => {
						            $message.success(data.msg)
						          })
						          addInvoiceForm.image = fileList.map(item => item.url).join('|')
						        }"
						        :before-remove="(file, fileList) => {
						          return $confirm(`确定移除 ${file.name}？`)
						        }"
						        multiple
						        :limit="1"
						        :on-exceed="(files, fileList) =>{
						          $message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
						        }"
						        :file-list="imageArray">
						        <el-button size="small" type="primary">点击上传</el-button>
						        <div slot="tip" class="el-upload__tip">添加相关附件</div>
						      </el-upload>
						  </el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" type="primary" @click="closeAddInvoiceFormOne" plain>关闭</el-button>
				<el-button size="small" type="primary" @click="addInvoiceFormOne" plain>确定</el-button>
			</span>
		</el-dialog>
		<div class="bg-white top">
			<el-row>
				<!-- <el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:add')" type="primary"
					size="small" icon="el-icon-plus" @click="add()">新建</el-button>
				<el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:edit')" type="warning"
					size="small" icon="el-icon-edit-outline" @click="edit()" :disabled="dataListSelections.length != 1"
					plain>修改</el-button>
				<el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:del')" type="danger"
					size="small" icon="el-icon-delete" @click="del()" :disabled="dataListSelections.length <= 0" plain>
					删除
				</el-button> -->
				<el-button type="primary" size="small" plain @click="addInvoiceDlalog=true">新增发票</el-button>
				<el-button type="danger" size="small" icon="el-icon-delete" @click="del()" :disabled="dataListSelections.length <= 0" plain>删除</el-button>
				<el-button-group class="pull-right">
					<el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:import')"
						type="default" size="small" icon="el-icon-upload2" title="导入"
						@click="isImportCollapse = !isImportCollapse"></el-button>
					<el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:export')"
						type="default" size="small" icon="el-icon-download" title="导出" @click="exportExcel()">
					</el-button>
					<el-button type="default" size="small" icon="el-icon-refresh" @click="refreshList">
					</el-button>
				</el-button-group>
			</el-row>
			<el-table :data="dataList" size="small" height="calc(100% - 80px)" @selection-change="selectionChangeHandle"
			:cell-style="cellStyle" style="border:1px solid #d6cfe2;min-height: 400px;" :header-cell-class-name="cellHeadStyle" :row-class-name="tableRowClassName"
				@sort-change="sortChangeHandle" v-loading="loading" class="table">
				<el-table-column type="selection" header-align="center" align="center" width="50">
				</el-table-column>
				<el-table-column prop="sysuser.name" show-overflow-tooltip label="用户">
					<template slot-scope="scope">
						<el-link type="primary" :underline="false" @click="view(scope.row.id)">
							{{scope.row.sysuser.name}}</el-link>
					</template>
				</el-table-column>
				<el-table-column prop="invoiceDate" show-overflow-tooltip label="开票日期">
				</el-table-column>
				<el-table-column prop="checkCode" show-overflow-tooltip label="校验码">
				</el-table-column>
				<el-table-column prop="isaccount" show-overflow-tooltip label="是否报销">
					<template slot-scope="scope">
						{{ $dictUtils.getDictLabel("is_account", scope.row.isaccount, '-') }}
					</template>
				</el-table-column>
				<el-table-column prop="type" show-overflow-tooltip label="发票类型">
					<template slot-scope="scope">
						{{ $dictUtils.getDictLabel("invoicebill_type", scope.row.type, '-') }}
					</template>
				</el-table-column>
				<el-table-column prop="subType" show-overflow-tooltip label="细分发票类型"  width="110">
					<template slot-scope="scope">
						{{ $dictUtils.getDictLabel("sub_bill_type", scope.row.subType, '-') }}
					</template>
				</el-table-column>
				<el-table-column prop="invoiceCode" show-overflow-tooltip label="发票代码">
				</el-table-column>
				<el-table-column prop="invoiceNo" show-overflow-tooltip label="发票号码">
				</el-table-column>
				<el-table-column prop="noTaxAmount" show-overflow-tooltip label="金额">
				</el-table-column>
				<el-table-column prop="withTaxAmount" show-overflow-tooltip label="含税价格">
				</el-table-column>
				<el-table-column prop="payerTaxNo" show-overflow-tooltip label="购方税号">
				</el-table-column>
				<el-table-column prop="payerName" show-overflow-tooltip label="购方姓名">
				</el-table-column>
				<el-table-column prop="sellerTaxNo" show-overflow-tooltip label="销方税号">
				</el-table-column>
				<el-table-column prop="sellerName" show-overflow-tooltip label="销方姓名">
				</el-table-column>
				<el-table-column prop="invoiceType" show-overflow-tooltip label="报销类型">
					<template slot-scope="scope">
						{{ $dictUtils.getDictLabel("ticket_type", scope.row.subType, '-') }}
					</template>
				</el-table-column>
				<el-table-column prop="accountType" show-overflow-tooltip label="报销类别">
				</el-table-column>
				<el-table-column prop="invoiceContent" show-overflow-tooltip label="报销说明">
				</el-table-column>
				<el-table-column header-align="center" align="center" fixed="right" :key="Math.random()" width="200"
					label="点击查看">
					<template slot-scope="scope">
						<el-image style="width: 100px; height: 50px" :src="scope.row.dmzUrl"
							:preview-src-list="[scope.row.dmzUrl]"></el-image>
						<!-- <el-button type="text" icon="el-icon-view" size="mini" @click="view(scope.row.id)">查看</el-button> -->
						<!-- <el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:edit')"
							type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
						<el-button v-if="hasPermission('zhaohang:invoice:web:userticket:sysUserTicket:del')" type="text"
							icon="el-icon-delete" size="small" @click="del(scope.row.id)">删除</el-button> -->
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageNo"
				:page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" background
				layout="total, sizes, prev, pager, next, jumper">
			</el-pagination>
		</div>
		<!-- 弹窗, 新增 / 修改 -->
		<SysUserTicketForm ref="sysUserTicketForm" @refreshDataList="refreshList"></SysUserTicketForm>
	</div>
</template>

<script>
	import tableStyles from '../../../../../../utils/mixins.js'
	import SysUserTicketForm from './SysUserTicketForm'
	import UserSelect from '@/components/userSelect'
	export default {
		mixins: [tableStyles],	
		data() {
			return {
				searchForm: {
					  isaccount: '',
					  type: '',
					  subType: '',
					  invoiceCode: '',
					  invoiceNo: '',
					  invoiceDate: '',
					  payerName: '',
					  sellerName: ''
				},
				dataList: [],
				pageNo: 1,
				pageSize: 10,
				total: 0,
				orderBy: '',
				dataListSelections: [],
				isImportCollapse: false,
				loading: false,
				//新增发票
				addInvoiceDlalog:false,
				addInvoiceFormLoading:false,
				imageArray:[],
				addInvoiceForm:{
					image:"",
					invoiceContent:"", //报销说明
					invoiceType:"", //报销类型 0差旅 1非差旅
					accountType:"", //报销类别
				},
				cascaderKey: 1,
				valueData: [], //报销二，三级类目
				
			}
		},
		components: {
			UserSelect,
			SysUserTicketForm
		},
		activated() {
			this.refreshList();
			this.getBusssinessType();
		},
		methods: {
			// 搜索城市切换选项
			handleChange(e) {
				this.$refs.bussinessTypes.dropDownVisible = false; //监听值发生变化就关闭它
			},
			//点击label也可以进行选择
			handleSelect(event) {
				var that = this;
				this.$nextTick(() => {
					let d = document.getElementsByClassName("cascader1");
					if (d[0] && !d[0].onclick) {
						d[0].onclick = function(e) {
							if (e.target.className == "el-cascader-node__label") {
								e.target.previousElementSibling.click();
							}
						};
					}
				});
			},
			//得到报销类目等数据
			getBusssinessType() {
				this.$http({
					url: `/dlyrl/oa/claimexpenses/claimingExpenses/selectProcess`,
					method: 'get',
					params: {
						company: this.$store.state.user.companyId,
						id: 0
					}
				}).then(({
					data
				}) => {
					if (data && data.success) {
						this.valueData = data.list;
					}
				})
			},
			addInvoiceFormOne() {
			    this.$refs['addInvoiceForms'].validate((valid) => {
			        if (valid) {
						this.addInvoiceForm.accountType = this.addInvoiceForm.accountType.join(",")
			            this.addInvoiceFormLoading = true;
			            this.$http({
			                url: '/zhaohang/invoice/web/userticket/sysUserTicket/saveUserInvoice',
			                method: 'post',
			                params: {
			                    company: this.$store.state.user.companyId,
								userId:this.$store.state.user.id,
								...this.addInvoiceForm
			                }
			            }).then(({
			                data
			            }) => {
			                if (data) {
			                    this.addInvoiceFormLoading = false;
			                    if (data.success) {
			                        this.closeAddInvoiceFormOne();
									this.refreshList();
			                        this.$message.success(data.msg);
			                    }
			                }
			            })
			        }
			    })
			},
			closeAddInvoiceFormOne() {
			    this.addInvoiceDlalog = false;
			    this.$refs.addInvoiceForms.resetFields();
				this.imageArray=[];
				this.addInvoiceForm.image="";
			},
			// 获取数据列表
			refreshList() {
				this.loading = true
				this.$http({
					url: '/zhaohang/invoice/web/userticket/sysUserTicket/list',
					method: 'get',
					params: {
						'pageNo': this.pageNo,
						'pageSize': this.pageSize,
						'orderBy': this.orderBy,
						...this.searchForm
					}
				}).then(({
					data
				}) => {
					if (data && data.success) {
						this.dataList = data.page.list
						this.total = data.page.count
						this.loading = false
					}
				})
			},
			// 每页数
			sizeChangeHandle(val) {
				this.pageSize = val
				this.pageNo = 1
				this.refreshList()
			},
			// 当前页
			currentChangeHandle(val) {
				this.pageNo = val
				this.refreshList()
			},
			// 多选
			selectionChangeHandle(val) {
				this.dataListSelections = val
			},

			// 排序
			sortChangeHandle(obj) {
				if (obj.order === 'ascending') {
					this.orderBy = obj.prop + ' asc'
				} else if (obj.order === 'descending') {
					this.orderBy = obj.prop + ' desc'
				} else {
					this.orderBy = ''
				}
				this.refreshList()
			},
			// 新增
			add() {
				this.$refs.sysUserTicketForm.init('add', '')
			},
			// 修改
			edit(id) {
				id = id || this.dataListSelections.map(item => {
					return item.id
				})[0]
				this.$refs.sysUserTicketForm.init('edit', id)
			},
			// 查看
			view(id) {
				this.$refs.sysUserTicketForm.init('view', id)
			},
			// 删除
			del(id) {
				let ids = id || this.dataListSelections.map(item => {
					return item.id
				}).join(',')
				this.$confirm(`确定删除所选项吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.loading = true
					this.$http({
						url: '/zhaohang/invoice/web/userticket/sysUserTicket/delete',
						method: 'delete',
						params: {
							'ids': ids
						}
					}).then(({
						data
					}) => {
						if (data && data.success) {
							this.$message.success(data.msg)
							this.refreshList()
						}
						this.loading = false
					})
				})
			},
			// 导入成功
			uploadSuccess(res, file) {
				if (res.success) {
					this.$message.success({
						dangerouslyUseHTMLString: true,
						message: res.msg
					})
				} else {
					this.$message.error(res.msg)
				}
			},
			// 下载模板
			downloadTpl() {
				this.$utils.download('/zhaohang/invoice/web/userticket/sysUserTicket/import/template')
			},
			exportExcel() {
				let params = {
					...this.searchForm
				}
				this.$utils.download('/zhaohang/invoice/web/userticket/sysUserTicket/export', params)
			},
			resetSearch() {
				this.$refs.searchForm.resetFields()
				this.refreshList()
			}
		}
	}
</script>
